% 读取图片
img = imread('1123.jpg');

% 获取原始图片的尺寸
[originalHeight, originalWidth, ~] = size(img);

% 目标尺寸
targetWidth = 450;
targetHeight = 650;

% 计算宽高比
originalAspectRatio = originalWidth / originalHeight;
targetAspectRatio = targetWidth / targetHeight;

% 根据目标宽高比调整尺寸
if originalAspectRatio > targetAspectRatio
    % 如果原始图片的宽高比大于目标宽高比，以宽度为基准调整高度
    newWidth = targetWidth;
    newHeight = round(targetWidth / originalAspectRatio);
else
    % 如果原始图片的宽高比小于或等于目标宽高比，以高度为基准调整宽度
    newHeight = targetHeight;
    newWidth = round(targetHeight * originalAspectRatio);
end

% 调整图片尺寸
resizedImg = imresize(img, [newHeight, newWidth]);

% 创建目标尺寸大小的图像（复制最近的像素）
finalImg = imresize(img, [targetHeight, targetWidth]);

% 计算需要放置在目标图像中的位置
startRow = floor((targetHeight - newHeight) / 2) + 1;
startCol = floor((targetWidth - newWidth) / 2) + 1;

% 将调整后的图片放置在目标图像中
finalImg(startRow:startRow+newHeight-1, startCol:startCol+newWidth-1, :) = resizedImg;

% 填充上下或左右的空白区域为最近的像素颜色
% 填充上部
if startRow > 1
    for i = 1:startRow-1
        finalImg(i, startCol:startCol+newWidth-1, :) = finalImg(startRow, startCol:startCol+newWidth-1, :);
    end
end

% 填充下部
if startRow + newHeight <= targetHeight
    for i = startRow + newHeight:targetHeight
        finalImg(i, startCol:startCol+newWidth-1, :) = finalImg(startRow + newHeight - 1, startCol:startCol+newWidth-1, :);
    end
end

% 填充左边
if startCol > 1
    for i = 1:startCol-1
        finalImg(:, i, :) = finalImg(:, startCol, :);
    end
end

% 填充右边
if startCol + newWidth <= targetWidth
    for i = startCol + newWidth:targetWidth
        finalImg(:, i, :) = finalImg(:, startCol + newWidth - 1, :);
    end
end

% 显示最终图像
% imshow(finalImg);

% 保存最终图像
imwrite(finalImg, 'resized_image_filled.jpg','Quality',95);
